package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.exception.SystemException;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeExt;
import com.ruan.pojoExt.ResignExt;
import com.ruan.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private ParticipantService participantService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ResignService resignService;

    @Autowired
    PositionService positionService;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private CommonUserMapper commonUserMapper;

    @Autowired
    private CommonUserService commonUserService;

    @Autowired
    private PositionMapper positionMapper;

    @Value("${kejiu.path}")//必须是org.springframework.beans.factory.annotation提供的Value
    private String basePath;

//    @GetMapping("/exportToExcel")
//    public Result exportToExcel(){
//        try {
//            employeeService.exportToExcel();
////            String message = "导出成功！请到" + basePath + "Excel文件目录下查看";
//            return new Result(Code.DOWNLOAD_OK, message);
////            return new Result(Code.DOWNLOAD_OK,"导出成功！请到${basePath}\\Excel文件目录下查看");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(Code.DOWNLOAD_ERR,"导出失败！");
//        }
//    }

    @GetMapping("/checkEmployeeExists/{id}")
    public Result checkEmployeeExists(@PathVariable Integer id){
        if(employeeService.getById(id) == null){
            return new Result(Code.SELECT_ERR,"该员工信息不存在！");
        }
        return new Result(Code.SELECT_OK,"员工信息存在！");
    }

    @GetMapping("/exportToExcel")
    public ResponseEntity<byte[]> exportToExcel(){
        try {
            byte[] excelBytes = employeeService.exportToExcel();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "员工表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/getEmployeeInfo")
    public Result getEmployeeInfo(){
        return employeeService.getEmployeeInfo();
    }

    @GetMapping("/getCurrentDepartEmployeeInfo/{departId}")
    public Result getCurrentDepartEmployeeInfo(@PathVariable Integer departId){
        return employeeService.getCurrentDepartEmployeeInfo(departId);
    }

    @GetMapping("/getEmployeeId")
    public Long getEmployeeId(@RequestParam("phone") String phone){
//        System.out.println("当前登录用户的phone是"+phone);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper);
//        Long id = employee.getId();
        if (employee != null) {
            Long id = employee.getId();
            // 继续处理id的逻辑
            return id;
        } else {
            // 处理employee为null的情况
            return Long.valueOf(0);
        }
    }


    @GetMapping("/getEmployeeDetailInfo/{id}")
    public Result getEmployeeDetailInfo(@PathVariable Integer id){
//        System.out.println("传过来的id为："+id);
        Employee employee = employeeService.getById(id);
        EmployeeExt employeeExt = new EmployeeExt();
        BeanUtils.copyProperties(employee,employeeExt);

        Position position = positionService.getById(employee.getPositionId());
        if(position != null) {
            employeeExt.setPosition(position.getPname());
//            System.out.println("employee.getPositionId()是："+employee.getPositionId());
//            if(employee.getPositionId() == 1){//是总部的总经理
//                employeeExt.setPosition("总经理");
//                System.out.println("employeeExt.getPosition()是："+employeeExt.getPosition());
//            }
        }
        return new Result(Code.SELECT_OK,employeeExt);
    }

    @GetMapping("/becomeFullTime/{id}")
    public Result becomeFullTime(@PathVariable Integer id){
//        System.out.println("传过来的id为："+id);
        if (employeeService.becomeFullTime(id)){
            return new Result(Code.UPDATE_OK,"转正成功！");
        }
        return new Result(Code.UPDATE_ERR,"转正失败！");
    }

    @GetMapping("/deleteEmployee/{id}")
    @Transactional
    public Result deleteEmployee(@PathVariable Integer id){
//        System.out.println("deleteEmployee传来的id是"+id);
        Employee employee = employeeService.getById(id);
        if(employee == null){
            return new Result(Code.DELETE_ERR,"员工信息不存在，删除失败！");
        }
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getPhone,employee.getPhone());


        LambdaQueryWrapper<FileEntity> fileEntityWrapper = new LambdaQueryWrapper();
        fileEntityWrapper.eq(FileEntity::getEmployeeId,employee.getId());
        List<FileEntity> fileEntityList = fileMapper.selectList(fileEntityWrapper);
        if (fileEntityList.size()>0){
            for(FileEntity fileEntity : fileEntityList){
//                System.out.println("删除前清空对应文件的上传人id");
                //清空对应文件的上传人id
                fileService.update(new UpdateWrapper<FileEntity>().lambda()
                        .set(FileEntity::getEmployeeId,null)
                        .eq(FileEntity::getId,fileEntity.getId()));
            }
        }

        // 获取文件路径
        if(employee.getAvatar() != null){
            String filePath = basePath + employee.getAvatar();
            File file = new File(filePath);
            // 删除员工头像文件 && file.delete()
            if (file.exists() && file.isFile()) {
                file.delete();
//                System.out.println("员工头像清理成功");
            }
        }

//        LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(Participant::getEmployeeId,employee.getId());
//        participantService.remove(queryWrapper1);

        int rows1 = commonUserMapper.delete(queryWrapper);
        int rows2 = employeeMapper.deleteById(id);
        if (rows1 > 0 && rows2 > 0){
            return new Result(Code.DELETE_OK,"该员工的所有信息已清空！");
        } else if(rows1 == 0 && rows2 > 0){
            return new Result(Code.DELETE_OK,"清理了残留的员工信息");
        }else if(rows1 > 0 && rows2 == 0){
            return new Result(Code.DELETE_OK,"清理了残留的账号信息");
        }
        return new Result(Code.DELETE_ERR,"员工信息清空失败！");
    }

    @GetMapping("/dismissedEmployee/{id}")
    @Transactional
    public Result dismissedEmployee(@PathVariable Integer id){
//        System.out.println("dismissedEmployee传来的id是"+id);
        Employee employee = employeeService.getById(id);
        if(employee == null){
            return new Result(Code.UPDATE_ERR,"员工信息不存在，离职失败！");
        }
        if(employee.getStatus().equals("离职")){
            return new Result(Code.UPDATE_ERR,"该员工已经离职！");
        }
        if (employeeService.dismissedEmployee(id)){
            return new Result(Code.UPDATE_OK,"成功离职！");
        }
        return new Result(Code.UPDATE_ERR,"离职失败！");
    }

    @PostMapping("/searchEmployee")
    public Result searchEmployee(@RequestBody QueryEmployeeCondition queryEmployeeCondition){

        List<Employee> employeeList = employeeService.searchEmployeeByCondition(queryEmployeeCondition);
        if (employeeList!=null){
            return new Result(Code.SELECT_OK,employeeList,"查询成功");
        }
        return new Result(Code.SELECT_ERR,"查无此人！");
    }

    @PutMapping("/updateEmployee")
    public Result updateEmployee(@RequestBody Employee employee){
        //System.out.println("updateSelfInfo传来的employee是"+employee);
        //防止工号重复
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Employee::getId,employee.getId());
        queryWrapper.eq(Employee::getJobId,employee.getJobId());
        int count = employeeMapper.selectCount(queryWrapper);
        if(count > 0){
            return new Result(Code.SAVE_ERR,"该工号已存在！");
        }
        employeeMapper.updateById(employee);

        return new Result(Code.UPDATE_OK,"员工信息修改成功！");
    }



    /**
     * 分页条件查询
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param queryEmployeeCondition 查询条件
     * @return
     */
    @PostMapping("/selectByPageAndCondition/{currentPage}/{pageSize}")
    @ApiOperation(value = "员工分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "queryEmployeeCondition", value = "员工查询条件", required = false, paramType = "body", dataType = "QueryEmployeeCondition")
    })
//    @Cacheable(value = "employeeCache",
//            key = "#currentPage + '_' " +
//                    "+ #pageSize + '_' " +
//                    "+ #queryEmployeeCondition",
//            unless = "#result == null")
    public Result selectByPageAndCondition(@PathVariable int currentPage,
                       @PathVariable int pageSize,
                       @RequestBody QueryEmployeeCondition queryEmployeeCondition) {
//        System.out.println("selectByPageAndCondition传来的参数是："+currentPage+pageSize+queryEmployeeCondition);
        Page<Employee> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Employee> wrapper =new LambdaQueryWrapper<>();

        wrapper.like(queryEmployeeCondition.getName()!=null &&
                        !queryEmployeeCondition.getName().equals(""),
                Employee::getName,queryEmployeeCondition.getName());
        wrapper.like(queryEmployeeCondition.getJobId()!=null &&
                        !queryEmployeeCondition.getJobId().equals(""),
                Employee::getJobId,queryEmployeeCondition.getJobId());

        //没有账号的员工不用查
        LambdaQueryWrapper<CommonUser> commonUserQueryWrapper = new LambdaQueryWrapper<>();
        //把所有账号的手机号都查出来
        commonUserQueryWrapper.select(CommonUser::getPhone);
        List<CommonUser> commonUserList = commonUserMapper.selectList(commonUserQueryWrapper);
        List<String> phoneList = commonUserList.stream().map(CommonUser::getPhone).collect(Collectors.toList());
        wrapper.in(phoneList != null && phoneList.size() > 0,
                Employee::getPhone,phoneList);

        wrapper.like(queryEmployeeCondition.getStatus()!=null &&
                        !queryEmployeeCondition.getStatus().equals(""),
                Employee::getStatus,queryEmployeeCondition.getStatus());
        wrapper.orderByAsc(Employee::getJobId);
        Page<EmployeeExt> iPageExt=new Page<>();
        //page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
        employeeService.page(iPage,wrapper);
        BeanUtils.copyProperties(iPage,iPageExt,"records");
        //从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<Employee> records = iPage.getRecords();
        //item:遍历出来的每一个项目对象
        List<EmployeeExt> list = records.stream().map((item) -> {
            EmployeeExt employeeExt = new EmployeeExt();
            BeanUtils.copyProperties(item,employeeExt);//先填充入employee的普通属性

//            Department department = departmentService.getById(item.getDepartmentId());
//            if(department != null){//能查到员工的部门
//                String departmentName = department.getName();
//                employeeExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
//            }
            Position position = positionService.getById(item.getPositionId());
            if(position != null){
                employeeExt.setPosition(position.getPname());
            }
            return employeeExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
        //System.out.println("list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
//        return R.success(iPageExt);

        //        return employeeMapper.selectPage(iPage,wrapper);
        return new Result(Code.SELECT_OK,iPageExt);
    }

    /**
     * 分页+条件 查入职待审核的员工入职
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param queryEmployeeCondition 查询条件
     * @return
     */
    @PostMapping("/getAuditByPageAndCondition/{currentPage}/{pageSize}")
    @ApiOperation(value = "入职员工分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "queryEmployeeCondition", value = "入职员工查询条件", required = false, paramType = "body", dataType = "QueryEmployeeCondition")
    })
//    @Cacheable(value = "employeeAuditCache",
//            key = "#currentPage + '_' " +
//                    "+ #pageSize + '_' " +
//                    "+ #queryEmployeeCondition",
//            unless = "#result == null")
    public Result getAuditByPageAndCondition(@PathVariable int currentPage,
                        @PathVariable int pageSize,
                        @RequestBody QueryEmployeeCondition queryEmployeeCondition) {
//        System.out.println("getAuditByPageAndCondition传来的参数是："+currentPage+pageSize+queryEmployeeCondition);
        Page<Employee> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Employee> wrapper =new LambdaQueryWrapper<>();

        wrapper.like(queryEmployeeCondition.getName()!=null,Employee::getName,queryEmployeeCondition.getName());
        wrapper.eq(Employee::getStatus,"待审核");

        Page<EmployeeExt> iPageExt=new Page<>();//封装

        employeeService.page(iPage,wrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

        BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<Employee> records = iPage.getRecords();
        List<EmployeeExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
            EmployeeExt employeeExt = new EmployeeExt();//只有EmployeeExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,employeeExt);//先填充入employee的普通属性

            Position position = positionService.getById(item.getPositionId());
            if(position != null) {
                employeeExt.setPosition(position.getPname());
            }
            return employeeExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
        //System.out.println("list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
//        return R.success(iPageExt);

        // 创建 Result 对象
        Result result = new Result(Code.SELECT_OK, iPageExt);
        //System.out.println("AuditResult是什么："+result);
        // 返回结果
        return result; // 这个返回值将被用于缓存判断

//        return new Result(Code.SELECT_OK,iPageExt);
//        return employeeMapper.selectPage(iPage,wrapper);
    }


    @PostMapping("/getManagementAudit")
    public Result getManagementAudit() {
        LambdaQueryWrapper<Admin> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getStatus,Admin.Status.waitForCheck);
        List<Admin> list = adminMapper.selectList(wrapper);
        return new Result(Code.SELECT_OK,list);
    }

    @PutMapping("/agreedAdmin/{id}/{adminId}")
    public Result agreedAdmin(@PathVariable Integer id,
                              @PathVariable Integer adminId){
        try {
            employeeService.agreedAdmin(id,adminId);
            return new Result(Code.UPDATE_OK,"审批成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }

    @PutMapping("/agreed/{id}/{adminId}")
    public Result agreed(@PathVariable Integer id, @PathVariable Integer adminId){
        try {
            employeeService.agreed(id,adminId);
            return new Result(Code.UPDATE_OK,"审批成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }

    @PutMapping("/refuseAdmin/{id}")
    public Result refuseAdmin(@PathVariable Integer id){
        try {
            employeeService.refuseAdmin(id);
            return new Result(Code.UPDATE_OK,"审批成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }

    @PutMapping("/refuse/{id}")
    public Result refuse(@PathVariable Integer id){
        try {
            employeeService.refuse(id);
            return new Result(Code.UPDATE_OK,"审批成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }



    /**
     * 获得离职的人员待审核列表
     * @return
     *///IPage<Resign>
    @PostMapping("/getResignList/{currentPage}/{pageSize}")
    @ApiOperation(value = "离职员工分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "queryEmployeeCondition", value = "离职职员工查询条件", required = false, paramType = "body",
                    dataType = "QueryEmployeeCondition")
    })
//    @Cacheable(value = "employeeResignCache",
//            key = "#currentPage + '_' " +
//                    "+ #pageSize + '_' " +
//                    "+ #queryEmployeeCondition",
//            unless = "#result == null")//不能阻止缓存null值？？？unless = "#result.code == 20041"
    public Result getResignList(@PathVariable int currentPage,
                                @PathVariable int pageSize,
                                @RequestBody QueryEmployeeCondition queryEmployeeCondition) {
        //System.out.println("getResignList传来的参数是："+currentPage+pageSize+queryEmployeeCondition);

        Page<Resign> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Resign> wrapper =new LambdaQueryWrapper<>();
      //主要区别在于LambdaQueryWrapper使用Lambda表达式来构建查询条件，更加简洁和直观。
//        QueryWrapper<Resign> wrapper =new QueryWrapper<>();

        //姓名模糊搜索框
        LambdaQueryWrapper<Employee> employeeWrapper =new LambdaQueryWrapper<>();
        employeeWrapper.like(queryEmployeeCondition.getName()!=null,
                Employee::getName,queryEmployeeCondition.getName());//模糊查询
        List<Employee> employeeList = employeeMapper.selectList(employeeWrapper);
        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
//        wrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句queryEmployeeCondition.getName()!=null,
        //System.out.println("employeeIds是"+employeeIds);
//        wrapper.in(employeeIds.size() > 0,Resign::getEmployeeId, employeeIds);

        wrapper.eq(Resign::getStatus,"待审核");
//筛选出有账号的离职员工(理论上没有账号的根本不会离职)
        // 获取employee表中所有的phone值
        List<String> commonUserPhones = commonUserService.list().stream()
                .map(CommonUser::getPhone)
                .collect(Collectors.toList());
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询employee表中与commonUser表phone值相同的记录
        employeeLambdaQueryWrapper.in(commonUserPhones.size() > 0,
                Employee::getPhone, commonUserPhones);
// 调用service/mapper方法查询符合条件的记录
        List<Employee> employeeList1 = employeeService.list(employeeLambdaQueryWrapper);
        List<Long> employeeIds1 = employeeList1.stream().map(Employee::getId).
                collect(Collectors.toList());
//        List<Long> employeeIds1 = new ArrayList<>();
//                System.out.println("employeeIds1是"+employeeIds1);
//        wrapper.in(employeeIds1.size() > 0,Resign::getEmployeeId, employeeIds1);
// 创建一个新数组，长度为两个数组的长度之和
        List<Long> combinedEmployeeIds = new ArrayList<>(employeeIds.size() + employeeIds1.size());

// 将employeeIds1的元素复制到新List中
        combinedEmployeeIds.addAll(employeeIds);

// 将employeeIds2的元素复制到新List中
        combinedEmployeeIds.addAll(employeeIds1);

        wrapper.in(combinedEmployeeIds.size() > 0,Resign::getEmployeeId, combinedEmployeeIds);

        Page<ResignExt> iPageExt=new Page<>();//封装

        resignService.page(iPage,wrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

        BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<Resign> records = iPage.getRecords();
        List<ResignExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
            ResignExt resignExt = new ResignExt();//只有ResignExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,resignExt);//先填充入Resign的普通属性
            Long employeeId = item.getEmployeeId();

            Employee employee = employeeService.getById(employeeId);
//            Department department = departmentService.getById(departmentId);
            if(employee != null){//能查到员工
                resignExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                resignExt.setPhone(employee.getPhone());
            }
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                resignExt.setPosition(position.getPname());
            }
//            if(department != null){//能查到员工的部门
//                String departmentName = department.getName();
//                resignExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
//            }
            return resignExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
        //System.out.println("list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性

        // 创建 Result 对象
        Result result = new Result(Code.SELECT_OK, iPageExt);
       // System.out.println("ResignResult是什么："+result);
        // 返回结果
        return result; // 这个返回值将被用于缓存判断

//        return new Result(Code.SELECT_OK,iPageExt);
    }

    //同意离职审批
    @PutMapping("/agreeResign/{id}/{adminId}")
    public Result agreeResign(@PathVariable Integer id,
                              @PathVariable Integer adminId){

        try {
            resignService.agreeResign(id,adminId);
            return new Result(Code.UPDATE_OK,"审批成功！");
            //如果resignService.agreeResign(id, adminId)方法中抛出了SystemException异常，
            // 将捕获到该异常并返回异常中的错误代码和消息给调用者
        } catch (SystemException se) {
            se.printStackTrace();
            return new Result(se.getCode(), se.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
//可以使程序在遇到异常时不会崩溃，而是能够进行适当的处理并继续执行其他逻辑。
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }

    //拒绝离职审批
    @PutMapping("/refuseResign/{id}/{adminId}")
    public Result refuseResign(@PathVariable Integer id,@PathVariable Integer adminId){

        try {
            resignService.refuseResign(id,adminId);
            return new Result(Code.UPDATE_OK,"审批成功！");
            //如果resignService.refuseResign(id, adminId)方法中抛出了SystemException异常，
            // 将捕获到该异常并返回异常中的错误代码和消息给调用者
        } catch (SystemException se) {
            se.printStackTrace();//
            return new Result(se.getCode(), se.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
//            try-catch块用于捕获resignService.agreeResign(id,adminId)方法可能抛出的异常。
//            如果该方法执行时出现异常，异常将被捕获并打印堆栈跟踪，然后返回一个带有错误代码和消息的Result对象以指示审批失败
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }
    }


    @PutMapping("/updateSelfInfo/{oldPhone}")
    @Transactional
    public Result updateSelfInfo(@PathVariable String oldPhone,
                                 @RequestBody Employee employee){
//        System.out.println("updateSelfInfo传来的employee是"+oldPhone+employee);
        if(oldPhone == null || oldPhone.equals("")){
            return new Result(Code.SAVE_ERR,"请先登录！");
        }

        //防止邮箱重复
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Employee::getId,employee.getId());
        queryWrapper.eq(Employee::getEmail,employee.getEmail());
        int count1 = employeeMapper.selectCount(queryWrapper);
        if(count1 > 0){
            return new Result(Code.SAVE_ERR,"该邮箱已存在！");
        }
        //防止手机号重复
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.ne(Employee::getId,employee.getId());
        queryWrapper1.eq(Employee::getPhone,employee.getPhone());
        Employee employee2 = employeeMapper.selectOne(queryWrapper1);
        //用户表的手机号也要防止重复
        LambdaQueryWrapper<CommonUser> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.ne(CommonUser::getPhone,oldPhone);
        userQueryWrapper.eq(CommonUser::getPhone,employee.getPhone());
        int count = commonUserMapper.selectCount(userQueryWrapper);

        if(employee2!=null || count > 0){
            return new Result(Code.SAVE_ERR,"该手机号已存在！");
        }
        //防止工号重复
        LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.ne(Employee::getId,employee.getId());
        queryWrapper2.eq(Employee::getJobId,employee.getJobId());
        int count2 = employeeMapper.selectCount(queryWrapper2);
        if(count2 > 0){
            return new Result(Code.SAVE_ERR,"该工号已存在！");
        }
        //如果是修改头像，需要删除旧头像
        if(employee.getAvatar()!=null && !employee.getAvatar().equals("")){
            //把旧的员工信息查出来，对比图片是否有修改
            LambdaQueryWrapper<Employee> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(Employee::getPhone,oldPhone);
            Employee employee1 = employeeMapper.selectOne(queryWrapper3);
//            System.out.println(employee.getAvatar()+"头像对比"+employee1.getAvatar());
            if(!employee.getAvatar().equals(employee1.getAvatar())){
                //头像有修改，删除旧头像
                String filePath = basePath + employee1.getAvatar();
//                System.out.println("filePath是什么："+filePath);
                File file = new File(filePath);
                if (file.exists() && file.isFile()) {
                    file.delete();
//                    System.out.println("员工头像清理成功");
                }
            }
        }
        employeeMapper.updateById(employee);
        //user表里的手机号也要同时改
        LambdaQueryWrapper<CommonUser> userQueryWrapper1 = new LambdaQueryWrapper<>();
        userQueryWrapper1.eq(CommonUser::getPhone,oldPhone);
        CommonUser commonUser1 = commonUserMapper.selectOne(userQueryWrapper1);
        //传入新手机号
        if(commonUser1!=null){
            if(!oldPhone.equals(employee.getPhone()) &&
                    employee.getPhone()!=null &&
                    !employee.getPhone().equals("")){
                System.out.println("清我手机号？");
                commonUser1.setPhone(employee.getPhone());
            }
            commonUserService.updateById(commonUser1);
        }
        return new Result(Code.UPDATE_OK,"修改成功！");
    }

}
